﻿using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.Person.Repositories;

[UseDI(ServiceLifetime.Scoped)]
public class PersonCertificateSpecialityRepository : Repository<PersonCertificateSpeciality, DefaultDbContext>
{
    public PersonCertificateSpecialityRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
    {
    }

    public IEnumerable<PersonCertificateSpeciality> GetPersonCertificateSpecialitysByCetificteId(string cetificteId)
    {
        int areaVersion = EntityCacheService.GetAreaVersion("CetificteId", cetificteId);
        return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
        {
            return $"PersonCertificateSpecialitysByCetificteId:{cetificteId}:{areaVersion}";
        }, () =>
        {
            Sql sql = Sql.Builder
            .Select("id")
            .From("person_certificate_speciality")
            .Where("cetificte_id=@0", cetificteId);
            return sql;
        });
    }

    public IEnumerable<PersonCertificateSpeciality> GetPersonCertificateSpecialitysByCetificteIds(IEnumerable<string> cetificteIds)
    {
        if (cetificteIds == null || cetificteIds.Count() == 0)
            return Enumerable.Empty<PersonCertificateSpeciality>();
        Sql sql = Sql.Builder;
        sql.Select("id")
            .From("person_certificate_speciality");
        sql.Where("cetificte_id in (@0)", cetificteIds);
        var ids = DbContext.FetchFirstColumn<string>(sql);
        return PopulateEntitiesByEntityIds(ids);
    }
}